<template>
  <div class="sensitiveWord" id="sensitiveWord">
    <!-- 功能按钮 -->
    <div class="sensitiveWord_button">
      <a-button class="addButton" type="primary" 
      :disabled="!btnPerm.includes('creatAble')"
      @click="addRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        新建
      </a-button>
      <a-button class="importButton" :disabled="!btnPerm.includes('importAble')" @click="batchAddRecord">批量导入</a-button>
      <a class="download-btn" :class="{ disable: !btnPerm.includes('downloadAble') }" @click="downloadtemp">下载导入模版</a>
      <div class="searchContent">
        <a-input v-model:value="searchSensitiveWord" placeholder="搜索敏感词" style="width: 192px">
          <template #suffix>
            <i class="iconfont icon-search" @click="onSearch"></i>
          </template>
        </a-input>
      </div>
    </div>
    <!-- 表格展示部分 -->
    <baseTable :columns="columns.sensitiveWordColumns" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
      ref="sensitiveBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" @changePage="changePage">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('editAble') }" @click="eidtRecord(record)">{{ record.oparation[0] }}</a>
          <a-popconfirm placement="topRight" :disabled="!btnPerm.includes('creatAble')" @confirm="confirmDelete(record)">
            <template #title>
              <p style="width: 197px">
                删除之后，文章中被替换的词语将恢复到被替换之前的状态。
              </p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">{{ record.oparation[1] }}</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')">删除</a-button>
      </template>
    </baseTable>

    <!-- 新建敏感词模态框 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false" class="sensitive_modal">
      <template v-slot:body>
        <div>
          <a-form name="advanced_search" class="ant-advanced-search-form" autoComplete="off" :model="formState"
            ref="sensitiveFrom" v-if="isVisible">
            <template v-if="isAddOrEdit">
              <a-form-item :name="['sensitiveWord', 'value']" :label="formState.sensitiveWord.label"
                :rules="[formState.sensitiveWord.rule]">
                <a-input v-model:value="formState.sensitiveWord.value" show-count :maxlength="25" allow-clear />
              </a-form-item>
              <a-form-item :name="['replaceWord', 'value']" :label="formState.replaceWord.label"
                :rules="[formState.replaceWord.rule]">
                <a-input v-model:value="formState.replaceWord.value" show-count :maxlength="25" allow-clear />
              </a-form-item>
            </template>
            <template v-else>
              <a-form-item :name="['batchSensitiveWord', 'value']" :label="formState.batchSensitiveWord.label"
                :rules="[formState.batchSensitiveWord.rule]">
                <upload :action="props_upload.action" :fileList="props_upload.fileList" :accept="props_upload.accept"
                  :directory="props_upload.directory" :isAutoUpload="props_upload.isAutoUpload"
                  :listType="props_upload.listType" @uploadChangeFinished="uploadFiles">
                </upload>
              </a-form-item>
            </template>

            <a-form-item label="重复敏感词:" :rules="[{ required: true }]" v-if="!formState.id">
              <a-radio-group v-model:value="formState_redio">
                <a-radio value="1">覆盖重复项</a-radio>
                <a-radio value="2">跳过重复项</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-form>
        </div>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts">
export default {
  name: "敏感词",
};
</script>
<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, createVNode, computed } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import baseModal from "@/components/modal/baseModal.vue";
import upload from "@/components/upload/fileUpload.vue";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
import globalFun from "@/utils/global";
import { checksensitiveWord } from "./formRuler";
import {routerPerm} from '@/utils/common';
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}

//data
const btnPerm = ref<any[]>([]);
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
const searchSensitiveWord = ref<string | number>(""); //搜索框

//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
const sensitiveBaseTables = ref<any>(null); // basetable的ref
let rowSelection = ref<(string | number)[]>([]);
const deleteArr = ref<(string | number)[]>([]);

// 模态框数据
const sensitiveFrom = ref<any>("sensitiveFrom");
const isAddOrEdit = ref<boolean>(true); //判断是新家、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
const modAlProps: modeProp = reactive({
  width: "M",
  title: "新建敏感词",
});

const formState = reactive<dataSourceType>({
  sensitiveWord: {
    value: "",
    rule: {
      required: true,
      validator: checksensitiveWord,
      trigger: ["blur"],
      msg1: "敏感词不可为空！",
      msg2: "敏感词已存在于替换词中！",
      api: "fetchSensitiveWordTableUnique",
      id: "",
      params: "sensitiveWord",
    },
    label: "敏感词",
  },
  replaceWord: {
    value: "",
    rule: {
      required: true,
      validator: checksensitiveWord,
      trigger: ["blur"],
      msg1: "替换词不可为空！",
      msg2: "替换词已存在于敏感词中！",
      api: "fetchsenSitiveWordTableInsensitiveword",
      id: "",
      params: "replaceWord",
    },
    label: "替换词",
  },
  batchSensitiveWord: {
    //批量上传
    value: {}, //接收批量上传文件传来的emit('');
    trigger: ["change", "blur"],
    rule: { required: true, message: "上传文件不可为空！" },
    label: "上传文件:",
  },
  id: "",
});

// 模板文件上传配置
const props_upload = reactive<dataSourceType>({
  action: "", //
  accept: "xlsx,xls",
  directory: false,
  listType: "text",
  fileList: [], // 已上传的文件
  isAutoUpload: false, //是否自动上传
});
let formState_redio = ref<string | number>("1");
//模态框button按钮个数和文案修改
const buttons = ref<dataSourceType[]>([
  {
    text: "保存",
    "html-type": "submit",
    keepAlive: true,
  },
]);
// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
// computed
rowSelection = computed(() => {
  return sensitiveBaseTables.value.selectedRowKeys;
});

//methods
const addRecord = async () => {
  //新加敏感词模态框条件修改
  //添加敏感词数据
  formState.id = ""
  isVisible.value = true;
  isAddOrEdit.value = true;
  modAlProps.title = "新建敏感词";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
    {
      text: "保存并继续新建",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  formState.sensitiveWord.value = "";
  formState.replaceWord.value = "";
};
const batchAddRecord = async () => {
  //批量上传
  isVisible.value = true;
  isAddOrEdit.value = false;
  modAlProps.title = "批量导入敏感词";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

const eidtRecord = async (item: dataSourceType) => {
  if(!btnPerm.value.includes('editAble')) return
  //编辑敏感词数据
  isAddOrEdit.value = true;
  modAlProps.title = "编辑敏感词";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  formState.sensitiveWord.value = item.sensitiveWord;
  formState.replaceWord.value = item.replaceWord;
  formState.id = item.id;
  formState.sensitiveWord.rule.id = item.id;
  formState.replaceWord.rule.id = item.id;
  isVisible.value = true;
};
// 新添或编辑敏感词调取接口
const buttonMessage = async (msg: dataSourceType) => {
  //保存
  sensitiveFrom.value
    .validate()
    .then(() => {
      let params: dataSourceType = {
        dealWithType: +formState_redio.value,
        replaceWord: formState.replaceWord.value,
        sensitiveWord: formState.sensitiveWord.value,
        id: formState.id,
      };
      let type: string = modAlProps.title.includes("批量")
        ? ""
        : modAlProps.title.includes("编辑")
          ? "Edit"
          : "Add";
      if (type) {
        request[`fetchSensitiveWordTable${type}`](params)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              getRdecord();
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      } else {
        const param = new FormData(); // 创建form对象
        // param.append("files", options.file, options.file.name); // 通过append向form对象添加数据
        param.append(
          "file",
          formState.batchSensitiveWord.value.file,
          formState.batchSensitiveWord.value.file.name
        ); // 通过append向form对象添加数据
        param.append("dealWithType", `${formState_redio.value}`);
        request
          .fetchsensitiveWordUploadTemp(param)
          .then((res: dataSourceType) => {
            //直接调接口
            if (res.code === "00000 00000") {
              props_upload.fileList.push(formState.batchSensitiveWord.value);
              getRdecord();
              message.success(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      }

      isVisible.value = msg.text == "保存" ? false : true;
      props_upload.fileList = [];

    })
    .catch(() => { });
};
// 删除单个敏感词
const confirmDelete = async (item: any) => {
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};
//删除已选所有敏感词
const deleteSelectedAll = async () => {
  let keys: (string | number)[] = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "您确定删除选中的敏感词？删除后无法恢复",
      content: "删除之后，文章中被替换的词语将恢复到被替换之前的状态。",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",

      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};
const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除敏感词
  await request.fetchSensitiveWordTableDelete({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      getRdecord({});
    } else {
      message.error(res.message);
    }
  });
};
const onSearch = async () => {
  //搜索获取数据参数配置
  let datas: dataSourceType = {
    sensitiveWord: searchSensitiveWord.value,
  };
  getRdecord(datas);
};
const getRdecord = async (datas: dataSourceType = {}) => {
  // 获取表格数据
  const data: {} = {
    pageNumber: datas.pageNumber || pageCurrent.value,
    pageSize: datas.pageSize || pageSize.value,
    sensitiveWord: datas.sensitiveWord || "",
  };
  const telData = (await request.fetchSensitiveWordTable(data)) || {};
  let reqData = telData;
  let sourceData = ref<dataSourceType[]>([]);
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      ...item.middleDto,
      sensitiveWord: item.sensitiveWord,
      replaceWord: item.replaceWord,
      oparation: ["编辑", "删除"],
      num: index + 1,
      createUser: item.createUser,
      createTime: item.createTime,
      id: item.id,
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  sensitiveBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    let obj = getTableScroll(74, "sensitiveWord");
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
};
const downloadtemp = async () => {
  if(!btnPerm.value.includes('downloadAble')) return
  // 下载模板
  await request
    .fetchsensitiveWordDownloadTemp()
    .then((res: any) => {
      globalFun.downloadFile(res, "下载敏感词模板文件.xls");
    })
    .catch((err: any) => {
      console.log(err, 999129328139218);
      throw new Error(err);
    });
};
//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  let datas: dataSourceType = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  getRdecord(datas);
};
const uploadFiles = async (fileObj: dataSourceType) => {
  // 配置上传文件所需参数
  formState.batchSensitiveWord.value = fileObj;
};
//onmounted
onMounted(async () => {
  btnPerm.value = routerPerm()
  getRdecord();
});
</script>
<style lang="scss" scoped>
.sensitiveWord {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;
  overflow: hidden;

  .sensitiveWord_button {
    padding-bottom: 24px;
    display: flex;
    align-items: center;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      margin-right: 8px;
    }

    .download-btn {
      font-weight: 400;
      margin-left: 16px;
      line-height: 22px;
      height: 22px;
      font-size: 14px;
    }

    .download-btn:hover {
      // color: #1050C7;
    }

    .searchContent {
      margin-left: auto;
      margin-right: 0px;

      .icon-search {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);
        position: absolute;
        right: 12px;
        top: 0px;
      }
    }
  }

  :deep(.ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}

::v-deep(.ant-radio-wrapper) {
  margin-right: 16px;
}

:deep(.ant-form-item) {
  width: 596px;
  display: flex;

  // margin-left: 28px;
  .ant-form-item-control {
    width: 498px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 90px;
    text-align: right;
  }
}

:deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
  // margin-top: -5px;
  margin-bottom: 0px;
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}
</style>
<style>
.sensitive_modal .ant-modal-body {
  margin-bottom: 0px;
}
</style>
